var iconv = require('iconv-lite')
var stream = require('stream')
var Transform = stream.Transform;

function EncodeTransformer(options) {
	if (!(this instanceof EncodeTransformer))
		return new EncodeTransformer(options);
	var encode = options.encode;
	if(!encode){
		encode = 'gbk';
	}
	this.encode = encode;
	Transform.call(this, options);
	var SELF = this;
	this.transfer = function(input, output){
		input.pipe(SELF);
		SELF.on('data', function(chunk){
			output.write(chunk)
		})
	}
}

EncodeTransformer.prototype = Object.create(Transform.prototype, {
	constructor : {
		value : EncodeTransformer
	}
});

EncodeTransformer.prototype._transform = function(chunk, encoding, done) {
	var decodechunk = iconv.decode(chunk, this.encode);
//	console.log(iconv.encode(decodechunk, 'utf-8') + '')
	this.push(decodechunk);
	done();
}

exports.getEncodeTransformer = function(option){
	return new EncodeTransformer(option);
}